package com.sheng.project.mask;

import cn.hutool.core.codec.Base64;
import lombok.NoArgsConstructor;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Objects;

/**
 * @author liusheng
 * @date 2023/07/19
 */
@NoArgsConstructor
public class CryptUtil {

    private static final CryptUtil CRYPT_UTIL = new CryptUtil();

    private static Key key;

    static {
        key = new SecretKeySpec("mask172839499999".getBytes(StandardCharsets.UTF_8), "AES");
    }

    public static CryptUtil setKey(String k) {
        try {
            key = new SecretKeySpec(k.getBytes(StandardCharsets.UTF_8), "AES");
        } catch (Exception var2) {
            var2.printStackTrace();
        }
        return CRYPT_UTIL;
    }

    public static String encrypt(String str) {
        byte[] encrypt = null;
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getEncoded(), "AES");
            cipher.init(1, secretKeySpec);
            encrypt = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        } catch (Exception var4) {
            var4.printStackTrace();
        }
        return Base64.encode(encrypt);
    }

    public static String decrypt(String str) {
        byte[] decrypt = null;
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getEncoded(), "AES");
            cipher.init(2, secretKeySpec);
            decrypt = cipher.doFinal(Base64.decode(str));
        } catch (Exception var4) {
            var4.printStackTrace();
        }
        return (new String(Objects.requireNonNull(decrypt))).trim();
    }
}

